package com.moonshine.utils;

import com.moonshine.parser.models.ClassBaseSignature;
import com.moonshine.parser.models.ClassSignature;

public class SignatureTools {

	public static String getQualifiedName(String name) {
		String qualifedName = getPackageName(name);
		String className = getClassName(name);
		if (qualifedName != "")
			qualifedName += ":";
		return qualifedName + className;
	}

	public static String getQualifiedName(ClassBaseSignature classSig) {
		String qualifedName = classSig.name;
		if (qualifedName.indexOf(":") == -1) {
			if (classSig.packageName != null
					&& classSig.packageName.length() != 0)
				qualifedName = classSig.packageName + ":" + qualifedName;

		}
		return qualifedName;
	}

	static final CRC32 crc = new CRC32();

	public static int getClassCRCValue(ClassBaseSignature classSig) {
		return getClassCRCValue(getQualifiedName(classSig));
	}

	public static int getClassCRCValue(String qualifiedClassName) {
		return crc.crc32(qualifiedClassName);

	}

	public static int getClassCRCValue(String packageName, String name) {
		// TODO Auto-generated method stub

		return getClassCRCValue((packageName != null ? packageName + ":" : "")
				+ name);
	}

	public static String getPackageName(String packageName) {
		// TODO Auto-generated method stub
		if (packageName != null) {
			int lastIndex = packageName.lastIndexOf(".");
			if (lastIndex != -1
					&& packageName.substring(lastIndex + 1, lastIndex + 2)
							.matches("[A-Z]")) {
				return packageName.substring(0, packageName.lastIndexOf("."));
			} else if (packageName.indexOf(":") != -1) {
				return packageName.split(":")[0];

			} else if (lastIndex != -1) {
				return packageName;
			}
		}

		return "";

	}

	public static String getClassName(String name) {
		// TODO Auto-generated method stub
		if (name.indexOf(":") != -1) {
			String[] parts = name.split(":");
			return parts[parts.length - 1];
		} else if (name.indexOf(".") != -1) {
			return name.substring(name.lastIndexOf(".") + 1);
		}

		return name;

	}
}
